package com.lagou.client;

import com.alibaba.fastjson.JSONObject;
import com.lagou.service.RpcRequest;
import com.lagou.service.com.lagou.zookeeper.ServiceDiscovery;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;

public class RpcConsumer {

    //创建线程池对象
//    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

//    private static UserClientHandler userClientHandler;

    private String serviceAddress;

    private ServiceDiscovery serviceDiscovery;

    public RpcConsumer(String serviceAddress) {
        this.serviceAddress = serviceAddress;
    }

    public RpcConsumer(ServiceDiscovery serviceDiscovery) {
        this.serviceDiscovery = serviceDiscovery;
    }

    @SuppressWarnings("unchecked")
    public <T> T createProxy(final Class<?> interfaceClass) {
        return (T) createProxy(interfaceClass, "");
    }

    public Object createProxy(final Class<?> serviceClass,final String providerName){
        //借助JDK动态代理生成代理对象
        return  Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                String response = null;
                try {
                    String uuid = UUID.randomUUID().toString().replaceAll("-","");
                    RpcRequest rpcRequest = new RpcRequest();

                    String className = method.getDeclaringClass().getName();
                    String methodName = method.getName();

                    Class<?>[] parameterTypes = method.getParameterTypes();

                    rpcRequest.setRequestId(uuid);
                    rpcRequest.setClassName(className);
                    rpcRequest.setMethodName(methodName);
                    rpcRequest.setParameterTypes(parameterTypes);
                    rpcRequest.setParameters(args);
                    System.out.println("------------------->rpcRequest :"+ JSONObject.toJSONString(rpcRequest));

                    // 获取 RPC 服务地址
                    if (serviceDiscovery != null) {
                        String serviceName = serviceClass.getName();

                        serviceAddress = serviceDiscovery.discover(serviceName);
                        System.out.println("discover service: "+ serviceName +"============"+ serviceAddress);
                    }
                    if (serviceAddress == null) {
                        throw new RuntimeException("server address is empty");
                    }

                    // 从 RPC 服务地址中解析主机名与端口号
                    String[] array = serviceAddress.split(":");
                    String host = array[0];
                    int port = Integer.parseInt(array[1]);

                    // 创建 RPC 客户端对象并发送 RPC 请求
                    RpcClient client = new RpcClient(host, port);
                    long time = System.currentTimeMillis();
                    response = client.send(rpcRequest);
                    long endTime = System.currentTimeMillis() - time;
                    System.out.println("time: " + endTime);

                }catch (Exception ex){
                    ex.printStackTrace();
                }

                if (response == null) {
                    System.out.println("------------------->  response is null");
                }

                return response;

            }
        });


    }



}
